﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using StarsAdmin.Core.Exceptions;
using StarsAdmin.Core.Models;
using System.Net;

namespace StarsAdmin.Web.Core.Filter
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionsFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<GlobalExceptionsFilter> _logger;

        public GlobalExceptionsFilter(ILogger<GlobalExceptionsFilter> logger)
        {
            _logger = logger;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常已经被处理
            if (context.ExceptionHandled)
            {
                return Task.CompletedTask;
            }
            string message = "系统错误，请联系管理员或者稍后再试。";
            var statusCode = HttpStatusCode.InternalServerError;

            switch (context.Exception)
            {
                case NotFoundException notFoundEx:
                    statusCode = HttpStatusCode.NotFound;
                    message = notFoundEx.Message;
                    break;

                case InUseException inUseEx:
                    statusCode = HttpStatusCode.Conflict;
                    message = inUseEx.Message;
                    break;
            }

            _logger.LogError(context.Exception, message);

            context.HttpContext.Response.StatusCode = (int)statusCode;

            var result = ResultModel<object>.Error(message, (int)statusCode);
            context.ExceptionHandled = true; // 将异常标记为已处理
            context.Result = new JsonResult(result);

            return Task.CompletedTask;
        }
    }
}